package com.example.aicooking.controller;

import com.example.aicooking.entity.ChatResponse;
import com.example.aicooking.entity.DifyProperties;
import com.example.aicooking.service.ImageService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@Slf4j
@RestController
@RequestMapping("/api/image")
public class ImageController {
    private final ImageService imageService;
    private final DifyProperties difyProperties;

    @Autowired
    public ImageController(ImageService imageService, DifyProperties difyProperties) {
        this.imageService = imageService;
        this.difyProperties = difyProperties;
    }

    @PostMapping("/upload")
    public ResponseEntity<?> uploadImage(
            @RequestParam("file") MultipartFile file,
            @RequestParam("userId") String userId) {
        String appId = "app1";
        try {
            // 验证appId是否有效
            if (!difyProperties.getApplications().containsKey(appId)) {
                return ResponseEntity.badRequest().body("无效的AI应用ID");
            }

            log.info("开始上传图片, userId: {}, appId: {}", userId, appId);
            return imageService.uploadImage(file, userId, appId);
        } catch (Exception e) {
            log.error("上传图片失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("上传失败: " + e.getMessage());
        }
    }

    @PostMapping("/chat")
    public ResponseEntity<ChatResponse> chatWithImage(
            @RequestParam String userId,
            @RequestParam String uploadFileId,
            @RequestParam String query,
            @RequestParam(value = "appId", defaultValue = "app1") String appId) {
        try {
            // 验证appId是否有效
            if (!difyProperties.getApplications().containsKey(appId)) {
                return ResponseEntity.badRequest().body(
                        ChatResponse.builder()
                                .status("error")
                                .errorMessage("无效的AI应用ID")
                                .build()
                );
            }

            log.info("开始图片对话, userId: {}, uploadFileId: {}, appId: {}", userId, uploadFileId, appId);
            ChatResponse response = imageService.chatWithImage(userId, uploadFileId, query, appId);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("图片对话失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ChatResponse.builder()
                            .status("error")
                            .errorMessage("处理失败: " + e.getMessage())
                            .build());
        }
    }
}